package com.king.demo;

import java.util.ArrayList;
import java.util.List;

import org.apache.xml.utils.res.LongArrayWrapper;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;

import com.king.util.BeanUtil;
import com.king.util.GlobalContext;

public class Economist {
    static Logger LOG = BeanUtil.getLOG(Economist.class);
    private static List<String> urls = new ArrayList<String>();
    private static final String baseUrl = "https://www.economist.com/sections/asia";

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", GlobalContext.CHROME_DRIVER);
        getUrls();
        run();
    }

    private static void getUrls() {
        WebDriver driver = new ChromeDriver();
        driver.get(baseUrl);
        List<WebElement> findElements = driver.findElements(By.className("teaser__link"));
        for (WebElement webElement : findElements) {
            urls.add(webElement.getAttribute("href"));
        }
        driver.quit();
    }

    @SuppressWarnings("finally")
    private static WebElement getWebElement(WebDriver driver, String className) {
        WebElement webEle = null;
        try {
            webEle = driver.findElement(By.className("flytitle-and-title__title"));
        } catch (NoSuchElementException e) {
            LOG.warn(className + "is not found");
        } finally {
            return webEle;
        }
    }

    private static void run() {
        for (String url : urls) {
            WebDriver driver = new ChromeDriver();
            // 打开页面
            driver.get(url);
            //
            WebElement webEle = null;
            // 标题
            webEle = getWebElement(driver, "flytitle-and-title__title");
            System.out.println(webEle.getText());
            // 简介
            webEle = getWebElement(driver, "blog-post__rubric");
            System.out.println(webEle.getText());
            // 图片
            webEle = getWebElement(driver, "blog-post__image-block");
            System.out.println(webEle.getAttribute("src"));
            // 发布时间
            webEle = getWebElement(driver, "blog-post__datetime");
            System.out.println(webEle.getText());
            // 正文
            webEle = getWebElement(driver, "blog-post__text");
            System.out.println(webEle.getAttribute("innerHTML"));
            driver.quit();
            //Crawler
        }
    }
}
